package Session

import (
	"fmt"
	"haochen233/horm/log"
	"haochen233/horm/schema"
	"reflect"
	"strings"
)

//Model 设置引用的表(即结构体解析后的表)
func (s *Session) Model(value interface{}) *Session {
	//仅在model的结构体类型变化时才进行Parse操作
	if s.refTable == nil || reflect.TypeOf(s.refTable.Model) != reflect.TypeOf(value) {
		s.refTable = schema.Parse(value, s.dialect)
	}
	return s
}

//RefTable
func (s *Session) RefTable() *schema.Schema {
	if s.refTable == nil {
		log.Error("Model is not set")
	}
	return s.refTable
}

//CreateTable 创建表
func (s *Session) CreateTable() error {
	table := s.RefTable()
	var columns []string
	for _, field := range table.Fields {
		columns = append(columns, fmt.Sprintf("%s %s %s", field.Name, field.Type, field.Tag))
	}

	desc := strings.Join(columns, ",")
	_, err := s.Raw("CREATE TABLE %s (%s);", table.Name, desc).Exec()
	return err
}

//HasTable 表是否存在
func (s *Session) HasTable() bool {
	sql, args := s.dialect.TableExistSQL(s.refTable.Name)

	row := s.Raw(sql, args...).QueryRow()
	var TABLE_NAME string
	err := row.Scan(&TABLE_NAME)
	if err != nil {
		log.Error(err)
	}
	return s.refTable.Name == TABLE_NAME
}
